var express = require('express');
var router = express.Router();
//引入数据库包
var db = require("../db.js");
var async = require('async');
/* GET home page. */
router.post('/login', function(req, res, next) { //登录
    let userid = req.body.username;
    let userpwd = req.body.userpwd;
    db.query("select * from person where id='" + userid + "'", function(err, rows) {
        if (err) {
            console.log(err.message);
            return;
        } else {
            if (rows.length > 0) {
                if (userpwd == rows[0].password) {
                    res.send({
                        status: 0,
                        msg: "登录成功",
                        data: {
                            userid: rows[0].id,
                            username: rows[0].name,
                            sex: rows[0].sex
                        }
                    });
                } else {
                    res.send({
                        status: 0,
                        msg: "密码错误",
                        data: null,
                    });
                }
            } else {
                res.send({
                    status: 0,
                    msg: "该用户不存在",
                    data: null,
                });
            }
        }
    })
});
//获取作品信息
router.get('/getwork', function(req, res, next) {
    var id = req.query.id
    db.query({
            sql: `select * from works;
            select checked from person  where id=${id};`,
        }, ['ace', 'xyf'],
        function(err, rows, fields) {
            if (err) {
                console.log(err.message);
                return;
            } else {
                var productinfo = rows[0]
                if (rows[1][0].checked) {
                    var checkedarr = rows[1][0].checked.split(',')
                    for (let obj of productinfo) {
                        if (checkedarr.indexOf((obj.productid).toString()) > -1) {
                            obj.checked = true
                        } else {
                            obj.checked = false
                        }
                    }
                } else {
                    productinfo[0].checked = false
                }
                res.send({
                    status: 0,
                    msg: "获取数据成功",
                    data: productinfo,
                });
            }
        }
    );
})

//获取个人信息
router.get('/getmyInfo', function(req, res, next) {
    let userId = req.query.userId;
    db.query(`select id,name,checked,over from person where id = ${userId}`, function(err, rows) {
        if (err) {
            console.log(err.message);
            return;
        } else {
            res.send({
                status: 0,
                msg: "获取数据成功",
                data: rows[0],
            });
            console.log(rows)
        }
    })
})

//投票
router.post('/vote', function(req, res, next) {
    let userId = req.body.userId;
    let productId = req.body.productId;
    if (new Date().getTime() > new Date("2018-10-26 18:00:00").getTime()) {
        res.send({
            status: 0,
            data: "投票已结束，感谢您的投票",
        });
    } else {
        db.query({
                sql: `update works set ballot=ballot+1,ballotPerson=if (ballotPerson is NUll or ballotPerson='', '${userId}', concat(ballotPerson, ',', '${userId}')) where productid = ${productId};
                    update person set checked = if(checked is NUll or checked='', '${productId}', concat(checked, ',', '${productId}')) where id = ${userId}; `,
            }, ['ace', 'xyf'],
            function(err, rows, fields) {
                if (err) {
                    throw err;
                } else {
                    res.send({
                        status: 0,
                        data: "投票成功",
                    });
                }
            }
        );
    }
})

//批量投票
router.post('/voteByList', function(req, res, next) {
    let userId = req.body.userId;
    let productIdlist = req.body.productIdList;
    if (new Date().getTime() > new Date("2018-10-26 18:00:00").getTime()) {
        res.send({
            status: 0,
            data: "投票已结束，感谢您的参与",
        });
    } else {
        db.query({
                sql: `update works set ballot=ballot+1,ballotPerson=if (ballotPerson is NUll or ballotPerson='', '${userId}', concat(ballotPerson, ',', '${userId}')) where productid in (${productIdlist});
                        update person set checked = if(checked is NUll or checked='', '${productIdlist}', concat(checked, ',', '${productIdlist}')) where id = ${userId}; `,
            }, ['ace', 'xyf'],
            function(err, rows, fields) {
                if (err) {
                    throw err;
                } else {
                    res.send({
                        status: 0,
                        data: "投票成功",
                    });
                }
            }
        );
    }
})

//结束投票
router.post('/over', function(req, res, next) {
    db.query("update person set over = 1", function(err, rows) {
        if (err) {
            console.log(err.message);
            return;
        } else {
            res.send({
                status: 0,
                msg: "成功",
            })
        }
    })
})

//确认投票
router.get('/confirm', function(req, res, next) {
    let userId = req.query.userId;
    db.query(`update person set over = 1 where id = ${userId}`, function(err, rows) {
        if (err) {
            console.log(err.message);
            return;
        } else {
            res.send({
                status: 0,
                msg: "成功",
            });
            console.log(rows)
        }
    })
})

//获取我的投票
router.get('/getmyVote', function(req, res, next) {
    let userId = req.query.userId;
    db.query(`select * from works where FIND_IN_SET(${userId}, ballotPerson)`, function(err, rows) {
        if (err) {
            console.log(err.message);
            return;
        } else {
            res.send({
                status: 0,
                msg: "获取数据成功",
                data: rows,
            });
            console.log(rows)
        }
    })
})

//获取总体投票信息
router.get('/getallVote', function(req, res, next) {
    let userId = req.query.userId;
    db.query(`select * from works order by ballot DESC`, function(err, rows) {
        if (err) {
            console.log(err.message);
            return;
        } else {
            res.send({
                status: 0,
                msg: "获取数据成功",
                data: rows,
            });
            console.log(rows)
        }
    })
})

//获取单个作品信息
router.get('/getworkInfoById', function(req, res, next) {
    let productId = req.query.productId;
    db.query(`select * from works where productid = ${productId}`, function(err, rows) {
        if (err) {
            console.log(err.message);
            return;
        } else {
            res.send({
                status: 0,
                msg: "获取数据成功",
                data: rows[0],
            });
            console.log(rows)
        }
    })
})

module.exports = router;